package controller

import (
	"context"
	"github.com/gin-gonic/gin"
	"net/http"
	"order-srv/internal/biz/dto"
	"order-srv/internal/biz/middleware"
	"order-srv/internal/biz/service"
	"order-srv/internal/biz/vo"
	"order-srv/libs"
)

type Order struct {
	Router
	orderService service.IOrder
}

// CreateOrder
// @Summary		 创建订单
// @Description  创建订单
// @Tags         order
// @Accept       json
// @Produce      json
// @Security 	 ApiKeyAuth
// @Param Authorization header string false "Bearer 用户令牌"
// @Param CreateOrder body dto.CreateOrder true "请求参数"
// @Success 200 {object} vo.Body "请求成功"
// @Failure 400 {object} vo.Body "请求错误"
// @Failure 500 {object} vo.Body "内部错误"
// @Router       /v1/order/create [post]
func (controller Order) CreateOrder(c *gin.Context) {
	var json dto.CreateOrder
	if err := c.ShouldBindJSON(&json); err != nil {
		controller.HandlerValidatorError(c, err)
		return
	}
	apiRes := vo.New()
	parentSpan, _ := c.Get("parentSpan")
	orderId, err := controller.orderService.CreateOrder(libs.CreateSpanContext(context.Background(), parentSpan), json)
	if err != nil {
		apiRes = vo.NewFail()
		apiRes.Msg = err.Error()
		c.JSON(http.StatusOK, apiRes)
		return
	}
	apiRes.Data = orderId
	c.JSON(http.StatusOK, apiRes)
}

func NewOrder(router *gin.Engine) {
	c := Order{
		orderService: service.NewOrder(),
	}

	r := router.Group("/v1/order")
	r.Use(
		middleware.Tracer(), // 链路追踪
	)
	// http://localhost:8080/health
	r.POST("/create", c.CreateOrder)
}
